import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { QAHistory, QARequest } from '../../types/qa';
import { qaApi } from '../../api/qa';

// 状态类型
interface QAState {
  history: QAHistory[];
  currentQA: QAHistory | null;
  loading: boolean;
  error: string | null;
}

// 初始状态
const initialState: QAState = {
  history: [],
  currentQA: null,
  loading: false,
  error: null,
};

// 异步Thunk - 提问
export const askQuestion = createAsyncThunk(
  'qa/ask',
  async (request: QARequest, { rejectWithValue }) => {
    try {
      return await qaApi.ask(request.question, request.knowledgeBaseId, request.topK);
    } catch (error) {
      return rejectWithValue('提问失败');
    }
  }
);

// 异步Thunk - 获取历史记录
export const fetchQAHistory = createAsyncThunk(
  'qa/fetchHistory',
  async ({ page, size }: { page: number; size: number }, { rejectWithValue }) => {
    try {
      return await qaApi.getHistory(page, size);
    } catch (error) {
      return rejectWithValue('获取历史记录失败');
    }
  }
);

// 异步Thunk - 搜索历史记录
export const searchQAHistory = createAsyncThunk(
  'qa/searchHistory',
  async ({ query, page, size }: { query: string; page: number; size: number }, { rejectWithValue }) => {
    try {
      return await qaApi.searchHistory(query, page, size);
    } catch (error) {
      return rejectWithValue('搜索历史记录失败');
    }
  }
);

// 异步Thunk - 获取单条历史记录
export const fetchQAHistoryById = createAsyncThunk(
  'qa/fetchHistoryById',
  async (id: number, { rejectWithValue }) => {
    try {
      return await qaApi.getHistoryById(id);
    } catch (error) {
      return rejectWithValue('获取历史记录详情失败');
    }
  }
);

// QA状态切片
const qaSlice = createSlice({
  name: 'qa',
  initialState,
  reducers: {
    clearCurrentQA: (state) => {
      state.currentQA = null;
    },
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    // 提问
    builder
      .addCase(askQuestion.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(askQuestion.fulfilled, (state, action: PayloadAction<QAHistory>) => {
        state.loading = false;
        state.currentQA = action.payload;
        state.history = [action.payload, ...state.history];
      })
      .addCase(askQuestion.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取历史记录
    builder
      .addCase(fetchQAHistory.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchQAHistory.fulfilled, (state, action: PayloadAction<QAHistory[]>) => {
        state.loading = false;
        state.history = action.payload;
      })
      .addCase(fetchQAHistory.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 搜索历史记录
    builder
      .addCase(searchQAHistory.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(searchQAHistory.fulfilled, (state, action: PayloadAction<QAHistory[]>) => {
        state.loading = false;
        state.history = action.payload;
      })
      .addCase(searchQAHistory.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取单条历史记录
    builder
      .addCase(fetchQAHistoryById.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchQAHistoryById.fulfilled, (state, action: PayloadAction<QAHistory>) => {
        state.loading = false;
        state.currentQA = action.payload;
      })
      .addCase(fetchQAHistoryById.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { clearCurrentQA, clearError } = qaSlice.actions;
export default qaSlice.reducer; 